package SmallClass

import (
	"OnlineRetailers/controllers/admin/PageNum"
	session2 "OnlineRetailers/controllers/admin/session"
	"OnlineRetailers/controllers/errorDeal"
	"OnlineRetailers/models"
	"OnlineRetailers/models/Admin"
	"OnlineRetailers/models/Admin/resMes"
	error2 "OnlineRetailers/models/errorDeal"
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

type GetSmallClass struct {
	beego.Controller
}

func (c *GetSmallClass) GetSmallClass() {
	defer func() {
		c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
		c.Ctx.Output.Status = 200
		c.ServeJSON()
	}()
	var addr = "/SmallClass/GetSmallClass"
	res := resMes.GetSmallClass{}
	smallClasses := []*Admin.SmallClass{}
	log := &error2.Log{}
	//mes := &error2.Mes{}
	var err error
	o := orm.NewOrm()
	Page, err := c.GetInt("Page", 0)
	begin, err := c.GetInt("begin", 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}
	err = session2.CheckSession(c.Ctx.Request.Header["Session"], 0)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	fmt.Println(begin)
	//sql := "select * from `activity`,`classification` Limit ?,?"
	//_, err = o.Raw(sql, begin, begin+models.DateLength).QueryRows(&activitys)
	_, err = o.QueryTable("SmallClass").Limit(models.AdminPage, models.AdminPage*Page).OrderBy("-SmallClassId").All(&smallClasses)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
		return
	}

	sql := "select * from `small_class_classifications` left join `classification` on `classification`.`classification_id`=`small_class_classifications`.`classification_id` where `small_class_classifications`.`small_class_id`=?"
	for i := 0; i < len(smallClasses); i++ {

		_, err = o.Raw(sql, smallClasses[i].SmallClassId).QueryRows(&smallClasses[i].Classification)
		if err != nil {
			c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, err.Error())
			return
		}
	}
	count, err := PageNum.GetPageNum("small_class", o)
	if err != nil {
		c.Data["json"] = errorDeal.ErrMess(log, "400", err, addr, "GetPageNum"+err.Error())
		return
	}
	res.Count = count / models.AdminPage
	res.SmallClass = smallClasses
	res.Code = "200"
	c.Data["json"] = res

}
